package com.warren.controller.lock;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @version V1.0
 * @Description:
 * @author: warren
 * @date: 2022/10/24 14:41
 */
@Slf4j
@RequestMapping("/lock")
@RestController
public class TestLock {
    @Autowired
    RedissonClient redissonClient;

    @GetMapping("/test")
    public void test() {
        RLock disLock = redissonClient.getLock("test");
        // 获取锁最多等待500ms，10s后key过期自动释放锁
        boolean tryLock = false;
        try {
            tryLock = disLock.tryLock(500, 10000, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (tryLock) {
            // 获取到锁后开始执行对资源的操作
            try {
                log.info("当前线程:[{}]获得锁", Thread.currentThread().getName());
                // 操作资源...
            } finally {
                disLock.unlock();
            }
        } else {
            log.info("当前线程:[{}]没有获得锁", Thread.currentThread().getName());
        }
    }

    @GetMapping("/testApi")
    public void testApi() {
        Map<String, String> user = new HashMap<>();
        user.put("user_id", "123456");
        user.put("mobile", "18888888888");
        user.put("address", "朝阳区百子湾街道某小区1单元101");
        user.put("city", "北京市");
        user.put("country", "中国");
        user.put("email", "heiz123@163.com");
        log.info("customer info: {}", JSON.toJSONString(user));
    }
}
